package org.onionframework.persistence.dao.expression;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.QueryException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.TypedValue;
import org.hibernate.persister.collection.QueryableCollection;
import org.hibernate.persister.entity.Loadable;
import org.hibernate.persister.entity.PropertyMapping;
import org.hibernate.sql.ConditionFragment;
import org.hibernate.type.CollectionType;
import org.hibernate.type.Type;
import org.onionframework.core.util.Reflections;

public abstract class ContainsExpression implements Criterion {

	private static final long serialVersionUID = -3852233902347740916L;

	private static final TypedValue[] NO_VALUES = new TypedValue[0];

	protected final String propertyName;
	protected final Criteria father;

	protected ContainsExpression(String propertyName, Criteria criteria) {
		this.propertyName = propertyName;
		this.father = criteria;
	}

	protected abstract boolean excludeHas();

	public final String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
		
		CriteriaQuery outerQuery = (CriteriaQuery)Reflections.getFieldValue(criteriaQuery, "outerQueryTranslator");
		String actualPropertyName = outerQuery.getPropertyName( propertyName );
		
		String elementEntityName = criteriaQuery.getEntityName( criteria, propertyName );
		
		String sqlAlias = criteriaQuery.getSQLAlias( criteria, propertyName );
		
		SessionFactoryImplementor factory = outerQuery.getFactory();
		QueryableCollection collectionPersister = getQueryableCollection( outerQuery.getEntityName(this.father,propertyName), actualPropertyName, factory );
		
		String[] collectionKeys = collectionPersister.getKeyColumnNames();
		String[] ownerKeys = ( ( Loadable ) factory.getEntityPersister( elementEntityName ) ).getIdentifierColumnNames();
		
		String fatherSqlAlias = outerQuery.getSQLAlias(this.father,propertyName);
		String[] fatherKeys = ( ( Loadable ) factory.getEntityPersister( outerQuery.getEntityName(this.father,propertyName) ) ).getIdentifierColumnNames().clone();
		for(int i =  0;i<fatherKeys.length;i++){
			fatherKeys[i] = fatherSqlAlias + "." +fatherKeys[i];
		}

		return sqlAlias + "." +  ownerKeys[0] + " " + (this.excludeHas() ? "not" : "") + " in (select hasTable." + collectionPersister.getElementColumnNames()[0] + " from " 
			+ collectionPersister.getTableName() 
			+ " hasTable where "
			+ new ConditionFragment().setTableAlias( "hasTable" ).setCondition( collectionKeys, fatherKeys ).toFragmentString()
			+ ")";
	}


	protected QueryableCollection getQueryableCollection(String entityName, String propertyName, SessionFactoryImplementor factory)
	        throws HibernateException {
		PropertyMapping ownerMapping = ( PropertyMapping ) factory.getEntityPersister( entityName );
		Type type = ownerMapping.toType( propertyName );
		if ( !type.isCollectionType() ) {
			throw new MappingException(
			        "Property path [" + entityName + "." + propertyName + "] does not reference a collection"
			);
		}

		String role = ( ( CollectionType ) type ).getRole();
		try {
			return ( QueryableCollection ) factory.getCollectionPersister( role );
		}
		catch ( ClassCastException cce ) {
			throw new QueryException( "collection role is not queryable: " + role );
		}
		catch ( Exception e ) {
			throw new QueryException( "collection role not found: " + role );
		}
	}

	public final TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery)
	        throws HibernateException {
		return NO_VALUES;
	}

	public final String toString() {
		return "contains fragment";//propertyName + ( excludeHas() ? " is not empty" : " is empty" );
	}

}
